package cn.jbooter.shiro.autoconfigure.config;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.servlet.Cookie;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

import cn.jbooter.shiro.autoconfigure.properties.IShiroProperties;

/**
 * Shiro rememberMe配置
 * @author HeJian
 *
 */
@ConditionalOnProperty(prefix = "spring.shiro.rememberMeManager" , name="enabled" ,havingValue="true")
public class ShiroRememberMeConfiguration {
	
	@Autowired
	protected IShiroProperties shiroProperties;
	
	/**
     * RememberMe配置之cookie配置
     * @return
     */
    @Bean
    public Cookie rememberMeCookie() {
    	SimpleCookie cookie = new SimpleCookie(shiroProperties.getRememberMeManager().getCookie().getName());
    	cookie.setHttpOnly(shiroProperties.getRememberMeManager().getCookie().isHttpOnly());
    	cookie.setDomain(shiroProperties.getRememberMeManager().getCookie().getDomain());
    	cookie.setMaxAge(shiroProperties.getRememberMeManager().getCookie().getMaxAge());
    	cookie.setPath(shiroProperties.getRememberMeManager().getCookie().getPath());
    	cookie.setSecure(shiroProperties.getRememberMeManager().getCookie().isSecure());
    	return cookie;
    }
    
    /**
     * RememberMe配置之rememberMe管理器
     * @return
     */
    @Bean
    public RememberMeManager rememberMeManager() {
    	CookieRememberMeManager mg = new CookieRememberMeManager();
    	mg.setCipherKey(Base64.decode(shiroProperties.getRememberMeManager().getBase64CipherKey()));//cipherKey是加密rememberMe Cookie的密钥；默认AES算法；
    	mg.setCookie(rememberMeCookie());
    	return mg;
    }
}
